package mc.contents.web.common;

import mc.contents.web.AsyncContextFactory;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Administrator on 14-12-9.
 */
public abstract class AbstractResponseHttpServlet extends HttpServlet {
    private static Logger log = LoggerFactory.getLogger( AbstractResponseHttpServlet.class );
    private String name;

    public AbstractResponseHttpServlet( String name ) {
        this.name = name;
    }

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse resp ) throws ServletException, IOException {
        String id = request.getParameter( "id" );
        String pageIndex = request.getParameter( "pageIndex" );

        if( StringUtils.isNotEmpty( id ) || StringUtils.isNotEmpty( pageIndex ) ){
            Long request_id = Long.valueOf( id );
            CommonContext context = AsyncContextFactory.get( name,request_id );
            if( context!=null ){
                CrawRequest crawRequest = context.getCrawRequest();
                CrawResult crawResult = setResult( request,request_id,pageIndex,crawRequest );

                AsyncContext asyncContext = context.getContext();
                Integer offset = crawRequest.getOffset();
                List<CrawResult> results = context.getCrawResults();

                if( results==null ){
                    results = new ArrayList<>( offset );
                    context.setCrawResults( results );
                }
                results.add( crawResult );

                //判断是否完成
                if( results.size() == offset ){
                    if( asyncContext.getRequest().isAsyncSupported() ){
                        asyncContext.complete();//爬取40页完成
                    }
                }
            }else{
                log.info( "this is a lazy callback ,id : "+ id+" ,pageIndex : "+ pageIndex );
            }

        }
    }

    public abstract CrawResult setResult( HttpServletRequest request, Long request_id, String pageIndex,CrawRequest crawRequest );
}
